package com.zymail.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zymail.bean.ZyAdmin;
import com.zymail.bean.ZyClass;
import com.zymail.bean.ZyGood;
import com.zymail.bean.ZyUser;
import com.zymail.service.ZyAdminService;
import com.zymail.service.ZyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    ZyUserService userService;
    @Autowired
    private ZyAdminService adminService;


    /**
     * 得到用户默认地址
     * @param session_key session_key
     * @return  用户默认地址di
     */
    @GetMapping("/getdefFloor/{session_key}")
    public Integer getdefFloor(@PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        return userService.getById(userId).getDefFloor();
    }
    @RequestMapping("/all")
    public Map<String,Object> all(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<ZyAdmin> wrapper = new QueryWrapper<>();
        wrapper.select().orderByDesc("id");

        List<ZyAdmin> list = adminService.list(wrapper);
        map.put("code",0);
        map.put("data",list);
        return map;

    }


    @RequestMapping("/del")
    public String del(ZyAdmin zyAdmin){
        adminService.removeById(zyAdmin.getId());
        return "succ";
    }

    @RequestMapping("/id")
    public ZyAdmin id(ZyAdmin zyAdmin){
        return adminService.getById(zyAdmin.getId());
    }


    @RequestMapping("/save")
    public String save(ZyAdmin zyAdmin,ZyUser zyUser,Integer uid){
        userService.saveOrUpdate(zyUser);
        QueryWrapper<ZyUser> wrapper = new QueryWrapper<>();
        wrapper.select().orderByDesc("id").last("limit 1");
        ZyUser user = userService.getOne(wrapper);

        if(uid!=null){
            zyAdmin.setUserId(uid);
        }else{
            zyAdmin.setUserId(user.getId());
        }

        adminService.saveOrUpdate(zyAdmin);

        return "succ";
    }

    /**
     * 修改用户默认地址
     * @param session_key   session_key
     * @param floorId   需要指定的地址id
     * @return  是否被修改完成
     */
    @PutMapping("/editdefFloor/{session_key}/{floorId}")
    public boolean editdefFloor(@PathVariable("session_key") String session_key,
                                @PathVariable("floorId") Integer floorId){
        Integer userId = get_userId(session_key);
        if(userId == 0) return false;

        ZyUser user = userService.getById(userId);
        user.setDefFloor(floorId);
        return userService.updateById(user);
    }
}
